You can use your browser's ability to stretch graphics along with JavaScript's math abilities to move beyond histograms to create actual Cartesian graphs of math functions.We're going to plot [y = sin(x)].
Discussion
Despite the fact that JavaScript has no native graphics capabilities (besides displaying bitmapped images), you can get away with a lot! In the histogram examples, bitmap repetition created the differently-sized bars. Here, bitmap stretching allows us to graph a mathematical function.The first thing you notice is that the graph is on its side. When you plot a function in x versus y, you know that x varies uniformly as you plot the graph (in this case, the angle theta plays the part of x, and we increment it by each time through the loop. The result of the calculation, y, on the other hand, doesn't vary so nicely. It can be either positive or negative for any given value of x. This makes it difficult to handle the graph if we make the y-axis vertical, as you might be used to seeing. Why?
Regardless of what we'd like to see done, the browser always works from left to right, top to bottom. If you're plotting a graph in its proper orientation, you'd have to plot all the positive function results first, and all the negative results second (because the positive results scale up to the top of the page, and the negatives down to the bottom) since you can only move across the page left-to-right, top-to-bottom. Our sine graph immediately starts in negative territory, which means that we can't plot those values, and would have to remember to do them once we crossed the x-axis of the graph.
This is a lot more trouble than it's worth.
It's easier to just plot down the page, with x running from negative to positive, and with the y-axis horizontal. If y suddenly becomes negative, this is no problem for us, because we can just plot the value right away and continue to the next value of x.
The next thing you notice is that the graph isn't centered in the page. This is because once we have nothing more to plot on a line, we stop. The <CENTER> tag centers the entire width of a line, and all the lines aren't the same width. If you pad all the positive results with the transparent graphic, you can center the graph, but this can also be more trouble than it's really worth. Alternately, you can forget centering and just put an extra transparent graphic padding the left side to get the graph off the left-hand side of the page.
Copyright ©1998 by Charles River Media, All Rights Reserved